package qc.powerjob.worker.processors.demo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import qc.module.demo.entity.OriginalScore;
import tech.powerjob.worker.core.processor.ProcessResult;
import tech.powerjob.worker.core.processor.TaskContext;
import tech.powerjob.worker.core.processor.sdk.BasicProcessor;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * 定时获取所有班级信息,保存获取的数据，处理数据并保存
 */
@Component
public class GetClassesDataProcessor implements BasicProcessor {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private HandleDataProcessor handleDataProcessor;

    //声明
    private static final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
        int i = 0;

        @Override
        public Thread newThread(@NotNull Runnable r) {
            return new Thread(r, "test-" + i++);
        }
    });

    @Override
    public ProcessResult process(TaskContext taskContext) throws Exception {

        System.out.println("开始获取数据");
        ServiceInstance service = discoveryClient.getInstances("module-demo").get(0);

        Map<String, Integer> map = new HashMap();
        map.put("no", 1);
        String url = "http://" + service.getHost() + ":" + service.getPort() + "/student/score/{no}";

        //设置编码
        restTemplate.getMessageConverters().set(0x1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        //调用第三方api获取原始数据
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class, map);
        String body = response.getBody();

        executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                //执行异步代码
                //调用处理数据的方法
                // 处理数据，处理完后保存数据库
                //handleData(service, body);
                TaskContext taskContext1 = new TaskContext();
                taskContext1.setJobParams(body);
                handleDataProcessor.process(taskContext1);
                return null;
            }
        });

        //继续执行，上面的代码块会异步执行不会等待
        //将原始数据保存在数据库
        addOriginalScoreData(service, body);

        return new ProcessResult(true, "数据获取完成");
    }

    /**
     * 保存原始数据
     *
     * @param service
     * @param responseBody
     * @return
     * @throws JsonProcessingException
     */
    private String addOriginalScoreData(ServiceInstance service, String responseBody) throws JsonProcessingException {
        System.out.println("保存原始数据");
        //将返回的原始数据保存在数据库中
        //json字符串转为list对象
        //将 JSON 字符串 转成 List：readValue
        //使用 readValue 方法，第一个参数是 JSON 字符串，第二个参数是转化的目标 TypeReference（类型参照）对象，这里指定其泛型为 List<OriginalScore>。
        ObjectMapper objectMapper = new ObjectMapper();
        List<OriginalScore> list = new ArrayList<>();
        if (responseBody != null) {
            System.out.println(responseBody);
            list = objectMapper.readValue(responseBody, new TypeReference<List<OriginalScore>>() {
            });
        }
        System.out.println(list);

        //请求头
        HttpHeaders headers = new HttpHeaders();

        //调用远程接口保存数据
        String url = "http://" + service.getHost() + ":" + service.getPort() + "/student/addOriginalScore";

        list.stream().forEach(originalScore -> {

            //设置请求参数，请求的接口参数为RequestBody对象
            HttpEntity<OriginalScore> httpEntity = new HttpEntity<OriginalScore>(originalScore, headers);

            //响应类型
            ParameterizedTypeReference<String> responseType = new ParameterizedTypeReference<String>() {
            };

            ResponseEntity<String> response = restTemplate.exchange(
                    url,//获取资源的地址
                    HttpMethod.POST, //请求类型
                    httpEntity, //请求实体
                    responseType //响应类型
            );
            String result = response.getBody();
            System.out.println(result + "-=-=原始数据保存成功-=-");
        });

        return null;
    }

    /**
     * 处理数据，计算成绩总分、平均分
     *
     * @param responseBody
     * @return
     * @throws JsonProcessingException
     */
    //public String handleData(ServiceInstance service, String responseBody) throws JsonProcessingException {
    //    System.out.println("处理数据");
    //    //json字符串转为list对象
    //    //将 JSON 字符串 转成 List：readValue
    //    //使用 readValue 方法，第一个参数是 JSON 字符串，第二个参数是转化的目标 TypeReference（类型参照）对象，这里指定其泛型为 List<OriginalScore>。
    //    ObjectMapper objectMapper = new ObjectMapper();
    //    List<OriginalScore> list = new ArrayList<>();
    //    if (responseBody != null) {
    //        System.out.println(responseBody);
    //        list = objectMapper.readValue(responseBody, new TypeReference<List<OriginalScore>>() {
    //        });
    //    }
    //    System.out.println(list);
    //
    //    //处理数据：计算成绩平均值、总分数
    //    List<Double> scoreList = new ArrayList<>();
    //    list.stream().forEach(originalScore -> {
    //        scoreList.add(originalScore.getScore().doubleValue());
    //    });
    //
    //    double sum = 0;
    //    for (int i = 0; i < scoreList.size(); i++) {
    //        sum += scoreList.get(i);
    //    }
    //    double avg = sum / scoreList.size();
    //    System.out.println("总分：" + sum + "，平均分：" + avg);
    //
    //    //保存处理好的数据到数据库
    //    double finalSum = sum;
    //    list.stream().forEach(originalScore -> {
    //        HandleScore handleScore = new HandleScore();
    //        handleScore.setCourseNo(originalScore.getCourseNo());
    //        handleScore.setDatetime(new Date());
    //        handleScore.setAvg(avg);
    //        handleScore.setSum(finalSum);
    //
    //        addHandleScoreData(service, handleScore);
    //    });
    //
    //    return null;
    //}

    ///**
    // * 保存处理好的数据
    // *
    // * @param handleScore
    // * @return
    // */
    //private String addHandleScoreData(ServiceInstance service, HandleScore handleScore) {
    //    System.out.println("保存处理好的数据");
    //    System.out.println(handleScore);
    //
    //    //调用远程接口保存数据
    //    String url = "http://" + service.getHost() + ":" + service.getPort() + "/student/addHandleScore";
    //
    //    //请求头
    //    HttpHeaders headers = new HttpHeaders();
    //
    //    //设置请求参数，请求的接口参数为RequestBody对象
    //    HttpEntity<HandleScore> httpEntity = new HttpEntity<HandleScore>(handleScore, headers);
    //
    //    //响应类型
    //    ParameterizedTypeReference<String> responseType = new ParameterizedTypeReference<String>() {
    //    };
    //
    //    ResponseEntity<String> response = restTemplate.exchange(
    //            url,//获取资源的地址
    //            HttpMethod.POST, //请求类型
    //            httpEntity, //请求实体
    //            responseType //响应类型
    //    );
    //    String result = response.getBody();
    //    System.out.println(result + "-----处理数据保存成功-----");
    //
    //    return null;
    //}
}
